package main

import "fmt"

// 限制同时处理的请求数

const MAXREQS = 50

var sem = make(chan int, MAXREQS)

type Request struct {
	a, b   int
	replyc chan int
}

func process(req *Request) {
	req.replyc <- (req.a*req.a + req.b*req.b - 2)
}

func handle(req *Request) {
	sem <- 1
	process(req)
	<-sem
}

func server(service chan *Request) {
	for {
		req := <-service
		go handle(req)
	}
}

func main() {
	chanReq := make(chan *Request)
	go server(chanReq)

	var reqs [20]Request
	for i := 0; i < 20; i++ {
		req := &reqs[i]
		req.a = i
		req.b = i + 20
		req.replyc = make(chan int)
		chanReq <- req
	}
	fmt.Println("print request reply")
	for ix := 19; ix >= 0; ix-- {
		req := &reqs[ix]
		fmt.Printf("%d: %d^2+%d^2-2 = %d\n", ix, req.a, req.b, <-req.replyc)
	}
}
